package io.bdmc.modules.bss.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.bdmc.common.annotation.SysLogger1;
import io.bdmc.common.exception.FileLengthNotEnoughException;
import io.bdmc.common.utils.*;
import io.bdmc.common.utils.Constant.ModifyName;
import io.bdmc.common.validator.Assert;
import io.bdmc.core.snmp.DeviceStatusProgress;
import io.bdmc.core.snmp.SORFileParserTool;
import io.bdmc.core.snmp.SnmpData;
import io.bdmc.core.snmp.SnmpTrapThreadPool;
import io.bdmc.core.snmp.cache.ConcurrentHashMapCacheUtils;
import io.bdmc.modules.bss.entity.*;
import io.bdmc.modules.bss.model.DeviceMeasureParam;
import io.bdmc.modules.bss.model.MeasureArgs;
import io.bdmc.modules.bss.model.SorEvent;
import io.bdmc.modules.bss.model.SorFileParser;
import io.bdmc.modules.bss.service.IDeviceDeviceService;
import io.bdmc.modules.bss.service.IDeviceMeasureEventService;
import io.bdmc.modules.bss.service.IDeviceMeasureService;
import io.bdmc.modules.sys.controller.AbstractController;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 设备测试 前端控制器
 * </p>
 *
 * @author ping
 * @since 2020-06-30
 */

// "设备测试相关接口", description = "/bss/device/measure")
@RestController
@RequestMapping("/bss/device/measure")
public class DeviceMeasureController extends AbstractController {

    @Autowired
    IDeviceMeasureService _devMeasureSvs;

    @Autowired
    IDeviceDeviceService _deviceDeviceSvs;

    @Autowired
    IDeviceMeasureEventService _eventSvs;

    @Autowired
    SnmpTrapThreadPool _snmpThreadPool;

    @GetMapping("/list")
    public R list(DeviceMeasureParam params) {
        MyPage<DeviceMeasure> myPage = new MyPage<>(params.getCurrent(), params.getSize());
        DeviceDevice dd = _deviceDeviceSvs.getById(params.getDeviceId());
        MyPage<DeviceMeasure> map;
        if (dd != null && dd.getDeviceDigest() != null && dd.getDeviceDigest().equals(Constant.IFMS1000)) {
            map = _devMeasureSvs.mySelectPageFor1U(myPage, params);
        } else {
            map = _devMeasureSvs.mySelectPage(myPage, params);
        }
        return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
    }

    @GetMapping("/curve")
    // "衰耗曲线图的数据", notes = "衰耗曲线图的数据")
    public R curve(DeviceMeasureParam params) {
        List<HashMap<String, Object>> list = _devMeasureSvs.selectForLine(params);
        return R.ok().putData(list);

    }

    @SysLogger1(value = "新增设备测试", entityType = DeviceMeasure.class, operationType = ModifyName.ADD)
    @PostMapping("/save")
    public R save(@RequestBody DeviceMeasure devicemeasure) {
        devicemeasure.setMeasureId(null);
        devicemeasure.setCreateBy(getUser().getUsername());
        devicemeasure.setCreateTime(LocalDateTime.now());
        devicemeasure.setDeptId(getDeptId().intValue());
        Boolean b = devicemeasure.insert();
        return R.trueOrFalse(b);
    }

    @SysLogger1(value = "修改设备测试", entityType = DeviceMeasure.class, operationType = ModifyName.UPDATE)
    @PostMapping("/update")
    // "修改DeviceMeasure", notes = "修改设备测试")
    // @RequiresPermissions("bss:device:measure:update")
    public R update(@RequestBody DeviceMeasure devicemeasure) {
        Boolean b = devicemeasure.updateById();
        return R.trueOrFalse(b);
    }

    // @SysLogger1(value = "删除设备测试历史记录", entityType = DeviceMeasure.class,
    // operationType = ModifyName.DELETE)
    @PostMapping("/delete")
    public R delete(@RequestBody long deviceId) {
        final LambdaQueryWrapper<DeviceMeasure> wrapper = Wrappers.lambdaQuery(DeviceMeasure.class)
                .eq(DeviceMeasure::getDeviceId, deviceId)
                .and(i -> i.isNull(DeviceMeasure::getStandard).or().ne(DeviceMeasure::getStandard, 1));

        boolean b = _devMeasureSvs.remove(wrapper);
        _eventSvs.deleteByMeasure();
        saveSysLog("删除", "测量记录", "删除所有测量记录", 0);
        return R.trueOrFalse(b);
    }

    @RequestMapping(value = "export")
    public R export(DeviceMeasureParam params) throws IOException {

        DeviceDevice dd = _deviceDeviceSvs.getById(params.getDeviceId());
        List<DeviceMeasure> list;
        if (dd != null && dd.getDeviceDigest() != null && dd.getDeviceDigest().equals(Constant.IFMS1000)) {
            list = _devMeasureSvs.exportListFor1U(params);
        } else {
            list = _devMeasureSvs.exportList(params);
        }
        if (list.size() > 50000) {
            return R.error("列表长度超过excel限制(50000)，请分批导出");
        }
        if (list.size() == 0) {
            return R.error("暂无数据。");
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("测试历史");
        String dateString = DateUtils.formatLocalDateTime(LocalDateTime.now(), DateUtils.Pay_DATE_TIME_PATTERN);
        String fileName = "设备" + list.get(0).getDeviceName() + "测试历史" + dateString + ".xls";// 设置要导出的文件的名字

        Map<String, CellStyle> styles = ExcelImport.createStyles(workbook);

        // 新增数据行，并且设置单元格数据
        int rowNum = 0;
        String[] headers = { "序号", "设备名称", "设备SN", "端口", "对应缆段纤芯", "测试类型", "光缆长度(km)", "衰耗（dB）", "测试时间" };

        rowNum = ExcelImport.initialize(rowNum, "设备" + list.get(0).getDeviceName() + "测试历史", headers, workbook, sheet,
                styles);

        // 在表中存放查询到的数据放入对应的列
        int dataIndex = 1;
        for (DeviceMeasure f : list) {
            HSSFRow row1 = sheet.createRow(rowNum++);
            row1.createCell(0).setCellValue(dataIndex);
            row1.createCell(1).setCellValue(f.getDeviceName());
            row1.createCell(2).setCellValue(f.getDeviceSn());
            // row1.createCell(2).setCellValue(ExcelImport.convertNullString(f.getDeviceIp()));
            row1.createCell(3).setCellValue(ExcelImport.convertNullString(f.getChannel()));
            row1.createCell(4).setCellValue(ExcelImport.convertNullString(f.getFibreCoreName()));
            row1.createCell(5).setCellValue(f.getAction() == 1 ? "自动测试" : "专家测试");
            row1.createCell(6).setCellValue(ExcelImport.convertNullString(f.getLength()));
            row1.createCell(7).setCellValue(ExcelImport.convertNullString(f.getPadControl()));
            row1.createCell(8).setCellValue(ExcelImport.convertNullString(f.getEndTime()));
            dataIndex++;
        }
        try {
            File path = new File(Constant.EXPORTPATH);
            if (!path.exists()) {
                path.mkdir();
            }
            File f = new File(path.getAbsolutePath() + "/excel/", fileName);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdir();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(f);// 指定路径与名字和格式
            workbook.write(fileOutputStream);// 将数据写出去
            fileOutputStream.close();// 关闭输出流
            return R.ok().putData("/excel/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(-1, e.getMessage());
        } finally {
            workbook.close();
        }
    }

    @PostMapping("/standard")
    // "设置标准值", notes = "设置标准值")
    // @RequiresPermissions("bss:device:measure:standard")
    public R standard(@RequestBody DeviceMeasure measure) {
        boolean result = false;
        if (measure.getMeasureId() > 0) {
            DeviceMeasure dbMeasure = _devMeasureSvs.getById(measure.getMeasureId());
            result = _devMeasureSvs.setStandardMeasure(dbMeasure);
        }
        return R.trueOrFalse(result);
    }

    @PostMapping("/args")
    @SysLogger1(value = "设置参数", entityType = MeasureArgs.class, operationType = ModifyName.ADD)
    // "设置参数", notes = "设置参数")
    public R args(@RequestBody MeasureArgs arg) {
        int deviceId = arg.getDeviceId();
        DeviceDevice dev = _deviceDeviceSvs.getById(deviceId);
        if (dev == null) {
            return R.error(-1, "参数错误");
        }
        Integer channel = arg.getChannel();
        String endPosition = arg.getEndPosition();
        String refIndex = arg.getRefIndex();
        String pulseWidth = arg.getPulseWidth();
        int action = arg.getAction();
        int time = arg.getTime();
        String resolution = arg.getResolution();
        boolean b = SnmpData.setSingleArgs(dev.getIpaddr(), channel, action, endPosition, refIndex, resolution,
                pulseWidth, time, dev.getWriteCode());
        return R.trueOrFalse(b);
    }

    @PostMapping("/testing")
    @SysLogger1(value = "单次测试或自动测试", entityType = MeasureArgs.class, operationType = ModifyName.ADD)
    // "单次测试或自动测试", notes = "单次测试或自动测试")
    public R testing(@RequestBody MeasureArgs arg) {
        int deviceId = arg.getDeviceId();
        DeviceDevice dev = _deviceDeviceSvs.getById(deviceId);
        if (dev == null) {
            return R.error(-1, "参数错误");
        }
        Integer channel = arg.getChannel();
        String endPosition = arg.getEndPosition();
        String refIndex = arg.getRefIndex();
        String pulseWidth = arg.getPulseWidth();
        int action = arg.getAction();
        String resolution = arg.getResolution();
        // boolean intelligentTest = arg.isIntelligentTest();// 智能测试
        int time = arg.getTime();

        int status = 0;
        switch (action) {
            case Constant.ACTION_AutoTest:
                status = 1;// 自动测试
                break;
            case Constant.ACTION_StopTest:
                status = 5;// 停止自动测试
                break;
            case Constant.ACTION_ManualTest:
                status = 2;// 专家测试
                break;
            default:
                break;
        }
        LocalDateTime now = LocalDateTime.now();
        String autoKey = Constant.MeasureNowMapPrefix + ":" + dev.getIpaddr() + ":" + Constant.ACTION_AutoTest + ":"
                + channel;
        String manualKey = Constant.MeasureNowMapPrefix + ":" + dev.getIpaddr() + ":" + Constant.ACTION_ManualTest + ":"
                + channel;
        synchronized (this) {
            // HashMap<String, DeviceMeasure> measureNowMap =
            // SnmpDataCache.getMeasureNowMap();
            if (action == Constant.ACTION_StopTest) {// 停止自动测试或智能测试
                // if (intelligentTest) {
                // SnmpDataCache.getIntelligentTestList().remove(dev.getIpaddr() + "," +
                // channel);
                // return R.ok().putData("操作成功，本次测试完成后会自动停止");
                // }
                boolean sendResult = SnmpData.setSingleMeasure(dev.getIpaddr(), channel, action, dev.getWriteCode());
                Wrapper<DeviceMeasure> w1 = new QueryWrapper<DeviceMeasure>().eq("action", "1").eq("measure_status", 1)
                        .eq("channel", channel).last("limit 1");
                DeviceMeasure existAuto = _devMeasureSvs.getOne(w1);
                if (existAuto != null) {
                    existAuto.setMeasureStatus(status);
                    existAuto.setEndTime(now);
                    existAuto.setAction(action);
                    existAuto.updateById();
                }
                // 移除缓存

                ConcurrentHashMapCacheUtils.deleteCache(autoKey);
                ConcurrentHashMapCacheUtils.deleteCache(manualKey);
                logger.info(dev.getIpaddr() + "停止测试:" + channel + ",result:" + sendResult);
                R.ok("操作成功,已向设备发送停止命令。");
            } else if (action == Constant.ACTION_AutoTest || action == Constant.ACTION_ManualTest) {// 开启专家或自动测试

                if (ConcurrentHashMapCacheUtils.getCache(autoKey) != null) {
                    return R.error(-1, "通道" + channel + "正在进行自动测试，请先停止自动测试");
                }
                if (ConcurrentHashMapCacheUtils.getCache(manualKey) != null) {
                    return R.error(-1, "通道" + channel + "正在进行专家测试，请先停止自动测试");
                }
                // 缓存中拿取动态数据
                DeviceMonitorDynamic dmc = (DeviceMonitorDynamic) ConcurrentHashMapCacheUtils
                        .getCache(Constant.DeviceMonitorDynamicPrefix + ":" + dev.getIpaddr());
                String[] portActiveArr = dmc.getPortActive().split(",");
                if (portActiveArr[channel - 1].equals("0")) {// 非空闲和非单次测试完成的状态不能启动测试
                    return R.error(-1, "通道" + channel + "不在位，无法测试");
                }
                SnmpData.setSingleMeasure(dev.getIpaddr(), channel, action, dev.getWriteCode());

                DeviceMeasure measure = new DeviceMeasure().setAverageNum(1).setDeviceId(deviceId)
                        .setDeviceIp(dev.getIpaddr()).setDeptId(dev.getDeptId()).setChannel(channel).setAction(action)
                        .setEndPosition(Integer.parseInt(endPosition)).setPulseWidth(Integer.parseInt(pulseWidth))
                        .setMeasureStatus(status).setStartTime(now).setDuration(time)
                        .setResolution(new BigDecimal(resolution)).setRefIndex(new BigDecimal(refIndex))
                        .setCreateBy(getUser().getUsername()).setCreateTime(now);
                if (action == Constant.ACTION_AutoTest) {
                    // 添加自动测试任务编号和次数，并放到缓存中
                    measure.setAutoTaskNum(CommonUtil.getOrderIdByUUId());
                    measure.setAutoTaskCount(0);
                }
                measure.insert();
                // 缓存本次测试
                String nowKey = Constant.MeasureNowMapPrefix + ":" + dev.getIpaddr() + ":" + action + ":" + channel;
                ConcurrentHashMapCacheUtils.setCache(nowKey, measure);
                return R.ok();
            }
        }
        return R.ok();
    }

    @GetMapping("/progress")
    // "获取所有通道的状态和测量进度", notes = "获取所有通道的状态和测量进度")
    public R getStatusProgress(int deviceId) {
        Assert.intIsLessEqZero(deviceId, "参数错误");
        DeviceDevice device = _deviceDeviceSvs.getById(deviceId);
        if (device != null && !StringUtils.isEmpty(device.getIpaddr())) {
            DeviceStatusProgress dsp = SnmpData.snmpAsyncWalkProgressStatus(device.getIpaddr(), device.getReadCode());
            return R.ok().putData(dsp);
        }
        return R.error(-1, "参数不正确");
    }

    @GetMapping("/status")
    // "获取指定设备和通道的测量状态", notes = "获取指定设备和通道的测量状态")
    public R getDeviceChannelStatus(MeasureArgs arg) {
        int deviceId = arg.getDeviceId();
        DeviceDevice dev = _deviceDeviceSvs.getById(deviceId);
        boolean st = false;
        if (dev != null && !StringUtils.isEmpty(dev.getIpaddr())) {
            // String intelligentKey = dev.getIpaddr() + "," + arg.getChannel();
            String key = Constant.MeasureNowMapPrefix + ":" + dev.getIpaddr() + ":" + arg.getAction() + ":"
                    + arg.getChannel();
            // 判断端口是否正在进行测试
            if (ConcurrentHashMapCacheUtils.isExist(key)) {
                DeviceStatusProgress dsp = SnmpData.snmpAsyncWalkProgressStatus(dev.getIpaddr(), dev.getReadCode());
                st = true;
                return R.ok().putData(st).put("progress", dsp);
            }
            return R.ok().putData(st);
        }
        return R.error(-1, "参数不正确");
    }

    @GetMapping("/standard")
    // "获取指定通道的标准值", notes = "获取指定通道的标准值")
    public R getStandard(int deviceId, int channel) {
        Assert.intIsLessEqZero(deviceId, "参数错误");
        Assert.intIsLessEqZero(channel, "参数错误");
        DeviceMeasure m = _devMeasureSvs.getOne(new QueryWrapper<DeviceMeasure>().eq("device_id", deviceId)
                .eq("standard", true).eq("channel", channel).orderByDesc("measure_id").last("LIMIT 1"));
        if (m == null) {
            return R.error(-1, "该通道未查询到标准值");
        }
        return parseSorAndEvent(m);

    }

    @GetMapping("/detail")
    // "获取指定测试的文件曲线", notes = "获取指定测试的文件曲线")
    public R getSorDetail(DeviceMeasureParam param) {
        DeviceMeasure measure = null;
        if (param.getMeasureId() != null && param.getMeasureId() > 0) {
            measure = _devMeasureSvs.getById(param.getMeasureId());
        } else if (StringUtils.isNotEmpty(param.getAutoTaskNum())) {
            measure = _devMeasureSvs.getOne(
                    Wrappers.lambdaQuery(DeviceMeasure.class).eq(DeviceMeasure::getAutoTaskNum, param.getAutoTaskNum())
                            .last("limit 1"));
        }

        return parseSorAndEvent(measure);
    }

    @GetMapping("/sor")
    // "获取指定通道最新sor文件曲线", notes = "获取指定通道最新sor文件曲线")
    public R getSorInfo(int deviceId, int channel, int action) {
        Assert.intIsLessEqZero(deviceId, "参数错误");
        Assert.intIsLessEqZero(channel, "参数错误");
        // Assert.intIsLessEqZero(action, "参数错误");
        if (action == 0) {
            DeviceMeasure m = _devMeasureSvs.getOne(new QueryWrapper<DeviceMeasure>().eq("device_id", deviceId)
                    .eq("channel", channel).orderByDesc("measure_id").isNotNull("sor_path").last("LIMIT 1"));
            return parseSorAndEvent(m);
        }
        DeviceMeasure m = _devMeasureSvs
                .getOne(new QueryWrapper<DeviceMeasure>().eq("device_id", deviceId).eq("channel", channel)
                        .eq("action", action).orderByDesc("measure_id").isNotNull("sor_path").last("LIMIT 1"));
        return parseSorAndEvent(m);
    }

    @GetMapping("/first")
    // "获取指定通道第一次sor文件曲线", notes = "获取指定通道第一次sor文件曲线")
    public R getFirst(int deviceId, int channel) {
        Assert.intIsLessEqZero(deviceId, "参数错误");
        Assert.intIsLessEqZero(channel, "参数错误");
        DeviceDevice dev = _deviceDeviceSvs.getById(deviceId);
        String filePath = downloadAutoTestFirstSor(dev.getIpaddr(), channel);
        if (StringUtils.isEmpty(filePath)) {
            return R.error(-1, "未查询到第一次测量sor文件");
        }
        SorFileParser sor;
        try {
            sor = SORFileParserTool.parserSorFile(filePath);
            HashMap<String, Object> map = new HashMap<>();
            map.put("sor", sor);
            if (sor != null) {
                List<SorEvent> sorEventsList = sor.getSorEvents();
                final List<SorEvent> refEvent = new ArrayList<>();// 所有反射点
                if (sorEventsList != null && sorEventsList.size() > 0) {
                    SorEvent endEvent = null;
                    for (SorEvent sorEvent : sorEventsList) {
                        if (sorEvent.getEventCode().contains("E")) {// 终端事件
                            sorEvent.setEventType("光纤终端");
                            sorEvent.setReflcetivity(null);
                            sorEvent.setEventLoss(null);
                            endEvent = sorEvent;
                        } else if (sorEvent.getEventCode().startsWith("1")) {// 反射事件
                            sorEvent.setEventType("反射点");
                            refEvent.add(sorEvent);
                        }
                    }

                    SorEvent firstEvent = new SorEvent();
                    firstEvent.setEventNumber(0);
                    firstEvent.setEventType("光纤始端");
                    sorEventsList.add(0, firstEvent);

                    // 计算总损耗
                    if (refEvent.size() == 0 && endEvent != null) {
                        BigDecimal totalLoss = new BigDecimal(endEvent.getEventPropagationDistance())
                                .multiply(BigDecimal.valueOf(endEvent.getAttenuationCoefficientLeadInFiber()));
                        endEvent.setTotalLosses(totalLoss.setScale(5, RoundingMode.HALF_DOWN).toString());
                    } else {
                        refEvent.sort(Comparator.comparing(SorEvent::getEventNumber));
                        for (int i = 0; i < refEvent.size(); i++) {
                            final SorEvent ev = refEvent.get(i);
                            BigDecimal distance;
                            if (i > 0) {
                                BigDecimal dis = new BigDecimal(refEvent.get(i - 1).getEventPropagationDistance());
                                distance = new BigDecimal(ev.getEventPropagationDistance()).subtract(dis);
                            } else {
                                distance = new BigDecimal(ev.getEventPropagationDistance());
                            }

                            final BigDecimal tloss = distance
                                    .multiply(BigDecimal.valueOf(ev.getAttenuationCoefficientLeadInFiber()))
                                    .add(new BigDecimal(ev.getEventLoss()).abs());
                            ev.setTotalLosses(tloss.setScale(3, RoundingMode.HALF_DOWN).toString());
                        }
                        if (endEvent != null) {
                            BigDecimal endLoss = new BigDecimal(endEvent.getEventPropagationDistance())
                                    .subtract(
                                            new BigDecimal(
                                                    refEvent.get(refEvent.size() - 1).getEventPropagationDistance()))
                                    .multiply(BigDecimal.valueOf(endEvent.getAttenuationCoefficientLeadInFiber()));
                            BigDecimal refTotalLoss = new BigDecimal(0);
                            for (SorEvent sorEvent : refEvent) {
                                refTotalLoss = refTotalLoss.add(new BigDecimal(sorEvent.getTotalLosses()));
                            }
                            endLoss = endLoss.add(refTotalLoss);
                            endEvent.setTotalLosses(endLoss.setScale(3, RoundingMode.HALF_DOWN).toString());
                        }

                    }

                }
            }
            return R.ok().putData(map);
        } catch (FileLengthNotEnoughException e) {
            logger.error(e.getMessage());
            return R.error(-1, "文件解析出错！");
        }
    }

    /**
     * 将测试的sor信息解析并组包
     *
     * @param m 测量信息
     */
    private R parseSorAndEvent(DeviceMeasure m) {
        if (m == null)
            return R.error(-1, "未查询到测量信息");
        SorFileParser sor;
        try {
            HashMap<String, Object> map = new HashMap<>();
            if (!StringUtils.isEmpty(m.getSorPath())) {
                sor = SORFileParserTool.parserSorFile(m.getSorPath());
                sor.setMeasureId(m.getMeasureId());
                map.put("sor", sor);
            }

            List<DeviceMeasureEvent> events = _eventSvs
                    .list(new QueryWrapper<DeviceMeasureEvent>().eq("measure_id", m.getMeasureId()));
            if (events != null) {
                events.sort(Comparator.comparing(DeviceMeasureEvent::getEventNumber));
            }
            map.put("measure", m);
            map.put("events", events);
            return R.ok().putData(map);
        } catch (FileLengthNotEnoughException e) {
            logger.error(e.getMessage());
            return R.error(-1, "文件解析出错！");
        }
    }

    // 下载sor文件
    private String downloadAutoTestFirstSor(final String ipaddr, final int channel) {
        String fileName = "IFMS_CH" + channel + "_SOR_First.sor";
        String path;
        String pathAndFileName = "/sor/" + fileName;
        File fileSor = new File(Constant.EXPORTPATH + pathAndFileName);
        if (fileSor.exists()) {
            fileSor.delete();
        }

        DeviceStatusStatic statusStatic = (DeviceStatusStatic) ConcurrentHashMapCacheUtils
                .getCache(Constant.DeviceStatusStaticPrefix + ipaddr);
        logger.info("准备下载文件：" + fileName);
        assert statusStatic != null;
        DeviceDevice dev = _deviceDeviceSvs.getById(statusStatic.getDeviceId());
        path = FTPUtils.downFile("/ram/", fileName, dev.getDeviceSn(), ipaddr, statusStatic.getFtpUserName(),
                statusStatic.getFtpUserPwd());
        if (StringUtils.isEmpty(path)) {
            return "";
        }
        File file1 = new File(Constant.EXPORTPATH + path);
        System.out.println(file1.exists());
        file1.renameTo(fileSor);
        return pathAndFileName;
    }
}
